package cn.johnyu.prsistencedemo;

import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private SharedPreferences pref;
    private SharedPreferences pref1;
    private SQLiteDatabase db;
    private JohnDbHelpler dbHelpler;
    private int i=0;
    private File sdcardDir;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref=PreferenceManager.getDefaultSharedPreferences(this);
        pref1=this.getSharedPreferences("john", MODE_PRIVATE);
        sdcardDir= Environment.getExternalStorageDirectory();

        dbHelpler=new JohnDbHelpler(this,sdcardDir.getAbsolutePath()+"/john1.db",null,2);
        db=dbHelpler.getWritableDatabase();
        Log.i("john", sdcardDir.getAbsolutePath() + "...............................");


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }

    public void writeData(View view) {
        SharedPreferences.Editor editor=pref1.edit();
        editor.putString("uname", "Tom");
        editor.putInt("age", 100);
        editor.commit();

    }
    public void readData(View view) {
        String uname=pref1.getString("uname","null");
        int age=pref1.getInt("age",-1);
        Log.i("john", uname + "....." + age);
    }
    public void writeDB(View view) {
        String sql="insert into users (uname) values (?)";
        try {
            db.beginTransaction();
            db.execSQL(sql, new Object[]{"john" + i++});
            db.setTransactionSuccessful();
        }
        catch (RuntimeException e){
        }
        finally {
            db.endTransaction();
        }
    }




    public void readDB(View view) {
        String sql="select uname,id from users where id>?";
        Cursor c=db.rawQuery(sql,new String[]{"2"});
        while (c.moveToNext()){
            String uname=c.getString(c.getColumnIndex("uname"));
            int id=c.getInt(c.getColumnIndex("id"));
            Log.i("john","uanme:"+uname+"........"+id);
        }
    }

    public void callQuery(View view) {
        Uri uri=Uri.parse("content://johnyu.cn");
        Cursor c=getContentResolver().query(uri, null, null, null, null);

    }
}
